package cn.tedu.charging.order.amqp;

import cn.tedu.charging.common.constant.AmqpComponentConst;
import cn.tedu.charging.common.pojo.message.DelayCheckMessage;
import cn.tedu.charging.order.service.OrderConsumerService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class AmqpConsumer {
    @Autowired
    private OrderConsumerService orderConsumerService;
    @Autowired
    private RedisTemplate redisTemplate;

    // 消费订单延迟消息的消费方法
    // 监听死信队列
    @RabbitListener(queues = AmqpComponentConst.DELAY_BILL_DL_QUEUE)
    public void consumeDlMessage(DelayCheckMessage msg, Message message, Channel channel) {
        // ToDo 考虑消费业务逻辑，实现消费
        log.debug("消费延迟（死信队列）消息：{}", msg);
        orderConsumerService.handleDelayResult(msg);
        // 除了可以获取消息体反序列化对象，还可以使用Message
        // 一样可以设置抢锁，保证县城安全
        String lockKey = "charging:device:result:" + msg.getOrderNo();
        // setnx <key(orderNo)> <value> ex 3
        Boolean getKey = redisTemplate.boundValueOps(lockKey).setIfAbsent("", 3, TimeUnit.SECONDS);
        // 执行成功 -> 手动确认
        try {
            if (getKey) {
                log.debug("获取锁成功,开始处理消息");
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            } else {
                log.debug("获取锁失败,结束消息消费");
            }
        } catch (Exception e) {
            log.error("消费延迟（死信队列）消息失败：{}", e.getMessage());
            throw new RuntimeException(e);
        }
        // 执行失败 -> 手动反馈拒绝消息，并重新投递 ToDo

    }
}
